// Package car_park_api
// @Author Spume
// @Date 2024-12-19

package car_park_api

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// Config API配置
type Config struct {
	Host     string        // 服务监听地址
	Port     int           // 服务监听端口
	APIHost  string        // 停车场API主机地址
	Timeout  time.Duration // 请求超时时间
	Debug    bool          // 调试模式
}

// DefaultConfig 默认配置
func DefaultConfig() *Config {
	return &Config{
		Host:    "localhost",
		Port:    8080,
		APIHost: DefaultParkHost,
		Timeout: 30 * time.Second,
		Debug:   false,
	}
}

// CarParkAPI 停车场API服务器
type CarParkAPI struct {
	config  *Config
	server  *http.Server
	service CarParkService
	handler *CarParkHandler
}

// NewCarParkAPI 创建停车场API服务器
func NewCarParkAPI(config *Config) *CarParkAPI {
	if config == nil {
		config = DefaultConfig()
	}
	
	// 创建服务和处理器
	service := NewCarParkService(config.APIHost)
	handler := NewCarParkHandler(service)
	
	// 创建HTTP服务器
	mux := http.NewServeMux()
	
	// 注册中间件
	mux.Handle("/", loggingMiddleware(recoveryMiddleware(corsMiddleware(mux))))
	
	// 注册路由
	handler.RegisterRoutes(mux)
	
	server := &http.Server{
		Addr:         fmt.Sprintf("%s:%d", config.Host, config.Port),
		Handler:      mux,
		ReadTimeout:  config.Timeout,
		WriteTimeout: config.Timeout,
		IdleTimeout:  config.Timeout * 2,
	}
	
	return &CarParkAPI{
		config:  config,
		server:  server,
		service: service,
		handler: handler,
	}
}

// Start 启动服务器
func (api *CarParkAPI) Start() error {
	log.Printf("Starting Car Park API server on %s", api.server.Addr)
	log.Printf("API Host: %s", api.config.APIHost)
	log.Printf("Debug Mode: %v", api.config.Debug)
	
	return api.server.ListenAndServe()
}

// Stop 停止服务器
func (api *CarParkAPI) Stop(ctx context.Context) error {
	log.Println("Stopping Car Park API server...")
	return api.server.Shutdown(ctx)
}

// Run 运行服务器（带优雅关闭）
func (api *CarParkAPI) Run() error {
	// 启动服务器
	go func() {
		if err := api.Start(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Failed to start server: %v", err)
		}
	}()
	
	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	
	// 优雅关闭
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	
	return api.Stop(ctx)
}

// GetService 获取服务实例
func (api *CarParkAPI) GetService() CarParkService {
	return api.service
}

// GetHandler 获取处理器实例
func (api *CarParkAPI) GetHandler() *CarParkHandler {
	return api.handler
}

// ============ 中间件 ============

// loggingMiddleware 日志中间件
func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		
		// 创建响应写入器包装器
		wrapped := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
		
		next.ServeHTTP(wrapped, r)
		
		duration := time.Since(start)
		log.Printf("%s %s %d %v", r.Method, r.URL.Path, wrapped.statusCode, duration)
	})
}

// recoveryMiddleware 恢复中间件
func recoveryMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				log.Printf("Panic recovered: %v", err)
				http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			}
		}()
		
		next.ServeHTTP(w, r)
	})
}

// corsMiddleware CORS中间件
func corsMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}
		
		next.ServeHTTP(w, r)
	})
}

// responseWriter 响应写入器包装器
type responseWriter struct {
	http.ResponseWriter
	statusCode int
}

func (rw *responseWriter) WriteHeader(code int) {
	rw.statusCode = code
	rw.ResponseWriter.WriteHeader(code)
}

// ============ 便捷函数 ============

// RunWithConfig 使用配置运行服务器
func RunWithConfig(config *Config) error {
	api := NewCarParkAPI(config)
	return api.Run()
}

// Run 使用默认配置运行服务器
func Run() error {
	return RunWithConfig(DefaultConfig())
}

// RunWithPort 使用指定端口运行服务器
func RunWithPort(port int) error {
	config := DefaultConfig()
	config.Port = port
	return RunWithConfig(config)
}

// RunWithEnv 使用环境变量配置运行服务器
func RunWithEnv() error {
	config := DefaultConfig()
	
	// 从环境变量读取配置
	if host := os.Getenv("CAR_PARK_HOST"); host != "" {
		config.Host = host
	}
	if port := os.Getenv("CAR_PARK_PORT"); port != "" {
		if p, err := fmt.Sscanf(port, "%d", &config.Port); err == nil && p == 1 {
			// 端口解析成功
		}
	}
	if apiHost := os.Getenv("CAR_PARK_API_HOST"); apiHost != "" {
		config.APIHost = apiHost
	}
	if debug := os.Getenv("CAR_PARK_DEBUG"); debug == "true" {
		config.Debug = true
	}
	
	return RunWithConfig(config)
}